package com.fallsvc.chatroom.controller;

import com.fallsvc.chatroom.common.Constants;
import com.fallsvc.chatroom.mapper.UserMapper;
import com.fallsvc.chatroom.model.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @auther falls_vc
 * description:
 * @date 2025/4/21  20:28
 */
@Slf4j
@RestController
public class UserController {
    @Resource
    private UserMapper userMapper;
    @PostMapping("/login")
    public Object login(@RequestParam String username,@RequestParam String password, HttpServletRequest request){
        // 1. 查找是否有该用户，密码是否匹配
        User user = userMapper.selectUserByUsername(username);
        if(user == null || !user.getPassword().equals(password)){
            // 登录失败返回null对象
            log.info("用户名或密码错误：查询User:{}",user);
            return new User();
        }
        // 隐藏密码
        user.setPassword("");
        // 2.登录成功创建会话
        HttpSession session=request.getSession(true);
        session.setAttribute(Constants.USER,user);
        return user;
    }
    @PostMapping("/register")
    public Object register(@RequestParam String username,@RequestParam String password){
        User user=null;
        try{
            user=new User();
            user.setUsername(username);
            user.setPassword(password);
            int insert = userMapper.insert(user);
            if(insert!=1){
                user=new User();
            }
            log.info("注册成功 user{}",user);
            user.setPassword("");
        }catch (DuplicateKeyException e){
            log.info("注册失败用户名重复 user:{}",user);
            user=new User();
        }

        return user;
    }

    @GetMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest request){
        // 1.获取会话
        HttpSession session=request.getSession(false);
        if(session==null){
            log.info("获取用户信息失败，没有创建session会话 {}",session);
            return new User();
        }
        // 2.获取用户对象
        User user=(User) session.getAttribute(Constants.USER);
        if(user==null){
            log.info("没有对应用户信息，user:{}",user);
            return new User();
        }
        //
        log.info("获得用户信息user{}",user);
        return user;
    }
}
